package com.chouxiaozi.dbroute.proxy;

import com.chouxiaozi.dbroute.IOrderService;
import com.chouxiaozi.dbroute.Order;
import com.chouxiaozi.dbroute.db.DynamicDataSourceEntity;

import java.text.SimpleDateFormat;
import java.util.Date;

public class OrderServiceStaticProxy implements IOrderService {

    private SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");

    private IOrderService orderService;

    public OrderServiceStaticProxy(IOrderService orderService){
        this.orderService = orderService;
    }

    @Override
    public int createOrder(Order order) {
        before(order);
        int i = this.orderService.createOrder(order);
        after();
        return i;
    }

    private void before(Order order) {
        Long time = order.getCreateTime();
        Integer dbRouter = Integer.valueOf(yearFormat.format(new Date(time)));
        System.out.println("静态代理类自动分配到【DB_" +  dbRouter + "】数据源处理数据" );
        DynamicDataSourceEntity.set(dbRouter);
    }

    private void after() {
        DynamicDataSourceEntity.restore();
    }
}
